
angular.module('U9ImHd.utility')
    .factory('Http', ['$q', '$http', 'Connect', 'APPCONSTANTS', function ($q, $http, Connect, APPCONSTANTS) {
        var o = {};

        o.request = function (cfg) {
            return http(cfg);
        };
        o.get = function (cfg) {
            cfg.method = 'Get';
            return http(cfg);
        };
        o.post = function (cfg) {
            cfg.method = 'POST';
            return http(cfg);
        };

        return o;

        function http (config) {
            var defer = $q.defer();

            if (!config.timeout) {
                config.timeout = APPCONSTANTS.httpTimeOut;
            }
            config.needOnLine = true;
            config.url = getFullURL(config.url, config.source);
            if (!config.url) {
                defer.reject();
            } else {
                $http(config).success(function (result) {
                    if (result.Data) {
                        defer.resolve(result.Data);
                    } else if (result.status === '0000') {
                        defer.resolve(result.data);
                    } else {
                        defer.reject(result.Error || result);
                    }
                }).error(function (err) {
                    defer.reject(err);
                });
            }

            return defer.promise;
        }

        function getFullURL (url, source) {
            // 0：数据采集系统；1：网关。默认为0
            source = source || 0;
            var address, port;
            if (source === 0) {
                address = Connect.get('address');
                port = Connect.get('port');
            } else if (source === 1) {
                address = Connect.getPortal('address');
                port = Connect.getPortal('port');
            }
            if (!address || !port) {
                return null;
            } else {
                return 'http://' + address + ':' + port + url;
            }
        }
    }]);